<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>联系人管理</el-breadcrumb-item>
      <el-breadcrumb-item>联系人列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入供应商" v-model="queryInfo.query" clearable @clear="getcontactList">
            <el-button slot="append" icon="el-icon-search" @click="getcontactList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openDialog()">添加联系人</el-button>
        </el-col>
      </el-row>

      <!-- 联系人列表区域 -->
      <el-table :data="contactlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="tid" prop="tid"></el-table-column>
        <el-table-column label="联系人姓名" prop="tname"></el-table-column>
        <el-table-column label="联系方式" prop="telephone"></el-table-column>
        <el-table-column label="供应商" prop="sname"></el-table-column>

        <el-table-column label="操作" width="160px">
          <template slot-scope="scope">
             <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.tid)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeContactById(scope.row.tid)"></el-button>
           
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加联系人的对话框 -->
    <el-dialog title="添加联系人" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="姓名" prop="tname">
          <el-input v-model="addForm.tname"></el-input>
        </el-form-item>
        <el-form-item label="供应商" prop="sid" >
          <el-select v-model="addForm.sid" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in supplierlist"
              :key="item.sid"
              :label="item.sname"
              :value="item.sid"
              
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="addForm.telephone"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addContact">确 定</el-button>
      </span>
    </el-dialog>
     <!-- 修改联系人的对话框 -->
    <el-dialog title="修改联系人" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="tid">
          <el-input v-model="editForm.tid" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editForm.tname" ></el-input>
        </el-form-item>
        <el-form-item label="供应商" >
          <el-select v-model="editForm.sid" style="width:100%">
            <el-option
              v-for="item in supplierlist"
              :key="item.sid"
              :label="item.sname"
              :value="item.sid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" >
          <el-input v-model="editForm.telephone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      contactlist: [],
      total: 0,
      // 控制添加零件对话框的显示与隐藏
      addDialogVisible: false,
      // 添加零件的表单数据
      addForm: {
        tname: '',
        sid: '',
        sname: '',
        telephone: ''
      },
      //供应商列表
      supplierlist: [],
      
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
       // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getcontactList()
    this.getSuplierList()
  },
  methods: {
    //获取联系人列表
    async getcontactList() {
      
      const { data: res } = await this.$http.get('cont/listCont', {
        params: this.queryInfo
      })
      if (res.meta.status == 200) {
        this.contactlist = res.data.conts
        this.total = res.data.total
        //return this.$message.success('获取零件列表！')
      } else {
        return this.$message.error('获取联系人列表失败！')
      }
      console.log(res)
    },
    //获取供应商列表
    async getSuplierList() {
     const { data: res } = await this.$http.get('comp/listSuppliers', {
      })
      if (res.meta.status == 200) {
        this.supplierlist = res.data.suppliers
        //return this.$message.success('获取供应商列表！')
      } else {
        return this.$message.error('获取供应商列表失败！')
      }
      console.log(res)
    },

    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getcontactList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getcontactList()
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //打开添加用户对话框
    async openDialog() {
      this.addDialogVisible = true
      console.log(res)
    },
    // 点击按钮，添加新用户
    addContact() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('cont/addContact', this.addForm)

        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败！')
        }

        this.$message.success('添加用户成功！')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getcontactList()
      })
    },
    // 展示编辑联系人的对话框
    async showEditDialog(tid) {
      
      const { data: res } = await this.$http.get('cont/getContact', {
         params:{'tid':tid} 
      })
      if (res.meta.status !== 200) {
        return this.$message.error('查询联系人信息失败！')
      }
      
      console.log(res)
      
      this.editForm = res.data.contact
      this.editDialogVisible = true
      
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.post('cont/updateContact',this.editForm)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新联系人信息失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getcontactList()
        // 提示修改成功
        this.$message.success('更新联系人信息成功！')
      })
    },
    // 根据Id删除对应的用户信息
    async removeContactById(tid) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该联系人, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.post('cont/deleteContact',{'tid':tid})

      if (res.meta.status !== 200) {
        return this.$message.error('删除联系人失败！')
      }

      this.$message.success('删除联系人成功！')
      this.getcontactList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
